# -*- coding: utf-8 -*-
# @Time    : 2019/11/13
# @Author  : CHENlj
# @File    : Request.py

"""
封装request

"""
import requests
from Common.Log import Mylog
from Common.Consts import TOKEN_FOREGROUND
import json


class Request:

    def __init__(self):
        pass

    @staticmethod
    def get_request(url, params=None, headers=None, cookies=None):
        """
        发起get请求
        :param url: 必填
        :param params: 选填
        :param headers: 选填
        :param cookies: 选填
        :return:
        """
        # if not url.startswith('http://'):
        #     url = "%s%s" % ("http://",url)
        #     print(url)

        try:
            if params is None:
                responce = requests.get(url, headers=headers, cookies=cookies)

            else:
                responce = requests.get(url, params=params, headers=headers, cookies=cookies)

        except requests.RequestException as e:
            print('%s%s' % ('RequestException url: ', url))
            Mylog.info(e)
            return ()

        # total_seconds为响应时间，单位为秒
        total_seconds = responce.elapsed.total_seconds()

        response_dicts = dict()
        try:
            response_dicts['body'] = responce.json()
        except Exception as e:
            print(e)
            response_dicts['body'] = ''
        response_dicts['code'] = responce.status_code
        response_dicts['text'] = responce.text
        response_dicts['total_seconds'] = total_seconds
        response_dicts['responce'] = responce

        return responce

    @staticmethod
    def post_request(url, data=None, json=None, headers=None, cookies=None):
        """
        发起post请求
        :param url:
        :param data:
        :param json:
        :param headers:
        :param cookies:
        :return:
        """
        # if not url.startswith("http://"):
        #     url = "%s%s" % ("http://",url)

        try:
            responce = requests.post(url, data=data, json=json, headers=headers, cookies=cookies)
        except requests.RequestException as e:
            print('%s%s' % ('RequestException url: ', url))
            Mylog.info(e)
            return ()

        # total_seconds为响应时间，单位为秒
        total_seconds = responce.elapsed.total_seconds()

        response_dicts = dict()
        response_dicts['status_code'] = responce.status_code
        try:
            response_dicts['body'] = responce.json()
        except Exception as e:
            print(e)
            response_dicts['body'] = ''

        response_dicts['text'] = responce.text
        response_dicts['total_seconds'] = total_seconds

        return responce

    @staticmethod
    def put_request(url, params=None, data=None, json=None, headers=None):
        """
        发起put请求
        :param url:
        :param params:
        :param data:
        :param headers:
        :return:
        """
        try:
            response = requests.put(url, params=params, data=data, json=json, headers=headers)
        except requests.RequestException as e:
            print('%s%s' % ('RequestException url: ', url))
            Mylog.info(e)
            return ()

        return response

    @staticmethod
    def del_requests(url, headers=None):
        try:
            response = requests.delete(url, headers=headers)
        except requests.RequestException as e:
            print('%s%s' % ('RequestException url: ', url))
            Mylog.info(e)
            return ()

        return response


if __name__ == "__main__":
    host = 'https://apimc1.vuewithreact.xyz/'
    get_addr_url = host + '/user/address_book'
    put_addr_url = host + '/user/address_book/16'
    post_addr_url = host + '/user/address_book'
    del_addr_url = host + '/user/address_book/18'

    # get请求参数
    params = {
        'page_size': 5,
        'currency_id': 1121
    }
    # get请求头
    headers = {
        'Authorization': TOKEN_FOREGROUND
    }

    # put请求参数
    params_put = {
        'id': 16
    }
    # put、post请求头
    headers_put = {
        'Content-Type': "application/json",
        'Authorization': TOKEN_FOREGROUND
    }
    # put请求体
    data_put = {
        "address": "lalalalalal",
        "currency_id": 1121,
        "remark": "ceshi3"
    }

    # post请求体
    data_post = {
        "address": "post_req",
        "currency_id": 1121,
        "memo": "",
        "remark": "post_request"
    }

    req = Request()
    # get请求
    ret = req.get_request(get_addr_url, params, headers)
    print(ret.json())
    li_obj = list(ret.json())[0]['id']
    print(li_obj)
    print(type(li_obj))
    # print(li_obj['id'])
    # print(json.dumps(li_obj))



    # put请求
    # ret2 = req.put_request(url=put_addr_url,json=data_put,headers=headers_put)
    # print(ret2.json())

    # post请求
    # ret_post = req.post_request(url=post_addr_url, json=data_post, headers=headers_put)
    # print(ret_post.json())

    # delete请求
    # ret_del = req.del_requests(del_addr_url,headers)
    # print(ret_del.status_code)

    # get请求
    # ret3 = req.get_request(get_addr_url, params, headers)
    # print(ret3.json())







